import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Friend() {
  const { user } = useAuth();
  const [friendId, setFriendId] = useState('');
  const [friends, setFriends] = useState([]);

  useEffect(() => {
    if (user) fetchFriends(user.student_id);
  }, [user]);

  const fetchFriends = async (sid) => {
    if (!sid) return;
    const res = await fetch(`/api/friend/${sid}`);
    const data = await res.json();
    if (data.success) setFriends(data.data);
  };

  const handleAdd = async (e) => {
    e.preventDefault();
    if (!user || !friendId) {
      alert('请填写好友学号');
      return;
    }
    const res = await fetch('/api/friend', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ student_id1: user.student_id, student_id2: friendId })
    });
    const data = await res.json();
    if (data.success) {
      setFriendId('');
      fetchFriends(user.student_id);
    } else {
      alert(data.message || '添加失败');
    }
  };

  return (
    <div className="card">
      <h2>好友管理</h2>
      <form onSubmit={handleAdd} style={{ marginBottom: 20, display: 'flex', gap: 12 }}>
        <input type="text" placeholder="好友学号" value={friendId} onChange={e => setFriendId(e.target.value)} />
        <button type="submit">添加好友</button>
      </form>
      <h3>好友列表</h3>
      <table>
        <thead>
          <tr><th>好友学号</th><th>姓名</th><th>成为好友时间</th></tr>
        </thead>
        <tbody>
          {friends.map(f => (
            <tr key={f.friend_id}>
              <td>{f.friend_id}</td>
              <td>{f.name}</td>
              <td>{new Date(f.since_time).toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
} 